package com.hbnu.zhouxunfa;
import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class MyRun implements Runnable{
    private Socket socket;
    public MyRun(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            String name = UUID.randomUUID().toString().replace('-','.');
            FileOutputStream fos = new FileOutputStream("E:\\CODE\\develop\\Websocaket\\serverdir\\"+name+".jpg");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int len;
            byte[] bytes = new byte[1024];
            System.out.println("图片接收中...");
            while ((len = bis.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
            System.out.println("图片接收完毕");
            //回显数据
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
